package com.scwatch.core.web.back;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scwatch.common.orm.RowSide;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.html.HtmlGenerator;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.CmsException;
import com.scwatch.core.support.Context;
import com.scwatch.ext.service.ScheduleJobService;
import com.scwatch.ext.service.impl.JobTaskServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.scwatch.core.constant.Constants.EDIT;
import static com.scwatch.core.constant.Constants.OPRT;

/**
 *  主播
 *
 * @author gujianlin
 *
 */
@Controller
@RequestMapping("/core/anchor")
public class AnchorController {
    private static final Logger logger = LoggerFactory.getLogger(AnchorController.class);

    public static final int INCLUDE_CHILDREN = 0;
    public static final int INCLUDE_MULTI = 1;
    public static final int MAIN_NODE = 2;

    /**
     * 查询主播相关新闻
     * @param queryNodeId 栏目id
     * @param queryNodeType 类型
     * @param queryInfoPermType 权限范围
     * @param queryStatus 状态
     * @param returnUrl 返回url
     * @param targetNodeId 目标栏目
     * @param orderId
     * @param nodeFlag 栏目标记
     * @param directoryId 爬虫文库
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("anchorRelateNewList.do")
    public String anchorRelateNewList(Integer queryNodeId, Integer queryNodeType, Integer queryInfoPermType, String queryStatus,
                           String returnUrl, Integer targetNodeId, Integer orderId, String nodeFlag, String directoryId,
                           @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC)Pageable pageable,
                           HttpServletRequest request, org.springframework.ui.Model modelMap) {
        String url="core/publish_center/info_list";
        if(returnUrl!=null){
            url="core/publish_center/"+returnUrl;
        }
        queryNodeType = queryNodeType == null ? 0 : queryNodeType;
        Integer siteId = Context.getCurrentSiteId();
        Site site=Context.getCurrentSite();
        User user = Context.getCurrentUser();

        Map returnMap = getFlagByNodeIds(Constants.CRAWLER_LIBRARY, siteId);

        Object nodes =null;

        if (returnMap != null){
            nodes=returnMap.get("nodes");
        }

        Integer nodeId = queryNodeId;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        if(Constants.CRAWLER_LIBRARY.equals(nodeFlag)) {
            if(returnUrl==null){
                url="core/publish_center/crawler_info_list";
            }
            nodeId=null;
        }else if(Constants.MODEL_FLAG_DRAFTS_NODE.equals(nodeFlag)){
            url="core/publish_center/crawler_info_list01";
            nodeId=null;
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        int infoPermType = user.getInfoPermType(siteId);
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }



        Integer[] nodeIds=null;
        if(Constants.CRAWLER_LIBRARY.equals(nodeFlag)) {
            if (directoryId != null && directoryId != ""){
                nodeIds = new Integer[]{Integer.valueOf(directoryId)};
            }else{

                nodeIds = (Integer[])returnMap.get("nodeIds");
            }
        }
        if(Constants.MODEL_FLAG_DRAFTS_NODE.equals(nodeFlag)){
            nodeIds=getNodeIdsByFlag(nodeFlag,siteId,null);
        }
        params.put("NOTEQ_newsType",new String[]{"10"});   //主播动态
        boolean allInfoPerm = user.getAllInfoPerm(siteId);
        Page<Info> pagedList = infoQuery.findAll(null,siteId, mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, pageable,nodeIds);
        List<Attribute> attributeList = attributeService.findList(siteId);

        if(queryNode!=null && queryNode.getNodeModel().getFlag().equals(Constants.MODEL_FLAG_ACTIVITY_NODE)){
            url="core/publish_center/info_activity_list";
        }
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("attributeList", attributeList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute("node",queryNode);
        modelMap.addAttribute("returnUrl",returnUrl);
        modelMap.addAttribute("targetNodeId",targetNodeId);
        modelMap.addAttribute("orderId",orderId);
        modelMap.addAttribute("nodes",nodes);
        modelMap.addAttribute("nodeFlag",nodeFlag);
        modelMap.addAttribute("directoryId",directoryId);
        //是否可以发布到直播盐都站点市州圈 0是 1否
        int isPubCity=1;
        if(site.getPublishNodeid()!=null && site.getPublishNodeid().intValue()>0){
            isPubCity=0;
        }
        modelMap.addAttribute("isPubCity",isPubCity);
        return "core/anchor/info_list";
    }

    /**
     * 查询全部主播动态
     * @param pageable 分页对象
     * @param city 市州
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequiresPermissions("core:anchor:dylist")
    @RequestMapping("dylist.do")
    public String dylist(@PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                          String city,
                          HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);

        //川台/市州 标记 区分
        Integer[] nodeIds = getNodeIdsByFlag(Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS, siteId,city);

        params.put("EQ_newsType",new String[]{"10"});   //主播动态
        Page<Info> pagedList = infoQuery.findAll(null, siteId, null, null, null, null, true, 1,null, params, pageable, nodeIds);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("city",city);
        return "core/anchor/anchor_dynamic_list";
    }

    /**
     * 修改主播动态是否精选
     * @param dynamicId 动态id
     * @param select 是否精选
     * @param request
     * @return 操作结果
     */
    @RequestMapping("updateDynamicSelect.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:anchor:updateDynamicSelect")
    @ResponseBody
    public String updateDynamicSelect(Integer dynamicId,Integer select,
                                      HttpServletRequest request) {
        String msg="fail";
        Site site=Context.getCurrentSite();
        User user=Context.getCurrentUser();
        String ip = Servlets.getRemoteAddr(request);
        if(dynamicId!=null && select!=null){
            Info info=infoQuery.get(dynamicId);
            if(info!=null){
                infoService.updateSelect(select,dynamicId);
                msg="success";
            }
            logService.operation("opr.info.updateDynamicSelect","修改主播动态是否精选:"+msg, select.toString(),dynamicId, ip, user.getId(), site.getId());
            logger.info("updateDynamicSelect,dynamicId={}.",dynamicId);
        }
        JSONObject json = new JSONObject();
        json.put("msg",msg);
        return json.toJSONString();
    }

    /**
     * 预览 主播动态
     * @param id
     * @param position
     * @param queryNodeId
     * @param returnUrl
     * @param queryParentId
     * @param city
     * @param queryNodeType
     * @param queryInfoPermType
     * @param queryStatus
     * @param pageable
     * @param request
     * @param modelMap
     * @return 结果页面
     */
//    @RequiresPermissions("core:anchor:edit")
    @RequestMapping("edit.do")
    public String edit(Integer id, Integer position, Integer queryNodeId, String returnUrl, Integer queryParentId,String city,
                          @RequestParam(defaultValue = "0") int queryNodeType, Integer queryInfoPermType, String queryStatus,
                          @PageableDefault(sort = {"publishDate", "id"}, direction = Sort.Direction.DESC) Pageable pageable,
                          HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite();
        User user = Context.getCurrentUser();
        Info bean = infoQuery.get(id);
        Backends.validateDataInSite(bean, site.getId());
        if (!bean.isDataPerm(user)) {
            throw new CmsException("accessDenied");
        }
        Integer nodeId = null;
        Integer mainNodeId = null;
        String treeNumber = null;
        Node queryNode = null;
        if (queryNodeId != null) {
            queryNode = nodeQuery.get(queryNodeId);
        }
        if (queryNode != null) {
            if (queryNodeType == INCLUDE_MULTI) {
                nodeId = queryNodeId;
            } else if (queryNodeType == MAIN_NODE) {
                mainNodeId = queryNodeId;
            } else {
                treeNumber = queryNode.getTreeNumber();
            }
        }
        Map<String, String[]> params = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX);
        Integer infoPermType = user.getInfoPermType(site.getId());
        if (queryInfoPermType != null && queryInfoPermType > infoPermType) {
            infoPermType = queryInfoPermType;
        }
        boolean allInfoPerm = user.getAllInfoPerm(site.getId());
        RowSide<Info> side = infoQuery.findSide(site.getId(), mainNodeId, nodeId, treeNumber, user.getId(), allInfoPerm,
                infoPermType, queryStatus, params, bean, position, pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);

        Node node = bean.getNode();
        Model model = bean.getModel();
        List<Attribute> attrList = attributeService.findList(site.getId());
        List<MemberGroup> groupList = memberGroupService.findList();
        String orgTreeNumber = site.getOrg().getTreeNumber();

        modelMap.addAttribute("model", model);
        modelMap.addAttribute("node", node);
        modelMap.addAttribute("attrList", attrList);
        modelMap.addAttribute("groupList", groupList);
        modelMap.addAttribute("orgTreeNumber", orgTreeNumber);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        modelMap.addAttribute("queryNodeType", queryNodeType);
        modelMap.addAttribute("queryInfoPermType", queryInfoPermType);
        modelMap.addAttribute("queryStatus", queryStatus);
        modelMap.addAttribute(OPRT, EDIT);
        modelMap.addAttribute("queryParentId", queryParentId);
        modelMap.addAttribute("city",city);
        return "core/anchor/anchor_dynamic_form";
    }


    @ModelAttribute
    public void preloadNodeBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Node bean = nodeQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                NodeDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new NodeDetail();
                    detail.setId(oid);
                    detail.setNode(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    @ModelAttribute
    public void preloadInfoBean(@RequestParam(required = false) Integer oid, org.springframework.ui.Model modelMap) {
        if (oid != null) {
            Info bean = infoQuery.get(oid);
            if (bean != null) {
                modelMap.addAttribute("bean", bean);
                InfoDetail detail = bean.getDetail();
                if (detail == null) {
                    detail = new InfoDetail();
                    detail.setId(oid);
                    detail.setInfo(bean);
                }
                modelMap.addAttribute("detail", detail);
            }
        }
    }

    private void validateIds(Integer[] ids, Integer siteId) {
        for (Integer id : ids) {
            Backends.validateDataInSite(nodeQuery.get(id), siteId);
        }
    }

    private Integer[] getInfoPermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getInfoPerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getNodePermIds(Integer siteId, Integer parentId) {
        Collection<Role> roles = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                roles = node.getNodePerms();
            }
        }
        if (roles == null) {
            roles = roleService.findList(siteId);
        }
        int len = roles.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (Role role : roles) {
            ids[i++] = role.getId();
        }
        return ids;
    }

    private Integer[] getViewGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getViewGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getContriGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getContriGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }

    private Integer[] getCommentGroupIds(Integer siteId, Integer parentId) {
        Collection<MemberGroup> groups = null;
        if (parentId != null) {
            Node node = nodeQuery.get(parentId);
            if (node != null) {
                groups = node.getCommentGroups();
            }
        }
        if (groups == null) {
            groups = memberGroupService.findList();
        }
        int len = groups.size();
        Integer[] ids = new Integer[len];
        int i = 0;
        for (MemberGroup group : groups) {
            ids[i++] = group.getId();
        }
        return ids;
    }
    private String[] splitTagKeywords(String tagKeywords) {
        String split = Constants.TAG_KEYWORDS_SPLIT;
        if (StringUtils.isNotBlank(split)) {
            for (int i = 0, len = split.length(); i < len; i++) {
                tagKeywords = StringUtils.replace(tagKeywords, String.valueOf(split.charAt(i)), ",");
            }
        }
        return StringUtils.split(tagKeywords, ',');
    }

    // 通过栏目模型id获取栏目
    private Map getFlagByNodeIds(String modelFlag,Integer siteId) {
        // 返回参数
        Map<String,Object> returnMap = new HashMap();
        JSONArray columns = new JSONArray();
        Integer [] nodeIds=null;

        Map<String,String[]> paramMap=new HashMap<>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        if (models == null || models.size() ==0){
            return  null;
        }

        String[] ids = new String[models.size()];
        String[] nodeNames = new String[models.size()];
        for(int i=0;i<models.size();i++){
            ids[i]=models.get(i).getId().toString();
            nodeNames[i]=models.get(i).getName();
        }
        paramMap=new HashMap<>();
        paramMap.put("EQ_nodeModel.id",ids);

        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList = nodeQuery.findList(siteId,null, null,null,true, paramMap, paramSort);

        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];

            for(int i=0;i<currentNodeList.size();i++){
                String name = currentNodeList.get(i).getName();

                for (int j=0;j<nodeNames.length;j++){
                    if (!name.equals(nodeNames[j])){
                        JSONObject node = new JSONObject();
                        node.put("id",currentNodeList.get(i).getId());
                        node.put("name",currentNodeList.get(i).getName());

                        nodeIds[i]=(currentNodeList.get(i).getId());
                        columns.add(node);
                    }
                }
            }
        }
        returnMap.put("nodes",columns);
        returnMap.put("nodeIds",nodeIds);
        return  returnMap;
    }

    private Integer[] getNodeIdsByFlag(String modelFlag,Integer siteId,String city) {
        Integer [] nodeIds=null;
        Map<String,String[]> paramMap=new HashMap<String,String[]>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        paramMap=new HashMap<String,String[]>();
        String[] idsStr;
        if(models!=null && models.size()>0){
            idsStr=new String[models.size()];
            for(int i=0;i<models.size();i++){
                idsStr[i]=models.get(i).getId().toString();
            }
            if(StringUtils.isNotBlank(city)){
               if("直播盐都".equals(city)){
                   paramMap.put("EQ_city",new String[]{"直播盐都"});
               }else{
                   paramMap.put("NOTEQ_city",new String[]{"直播盐都"});
               }
            }
            paramMap.put("EQ_nodeModel.id",idsStr);
        }
        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList=nodeQuery.findList(siteId,null,
                null,null,true,
                paramMap, paramSort);
        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];
            for(int i=0;i<currentNodeList.size();i++){
                nodeIds[i]=(currentNodeList.get(i).getId());
            }
        }
        return  nodeIds;
    }

    @Autowired
    private OperationLogService logService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MemberGroupService memberGroupService;
    @Autowired
    private WorkflowService workflowService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private NodeService nodeService;
    @Autowired
    private NodeQueryService nodeQuery;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private InfoQueryService infoQuery;
    @Autowired
    private InfoService infoService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private InfoNodeService infoNodeService;
    @Autowired
    private  FlashBigNewService flashBigNewService;
    @Autowired
    private JobTaskServiceImpl jobTaskService;
    @Autowired
    private ScheduleJobService scheduleJobMapper;
    @Autowired
    private HtmlGenerator htmlGenerator;


}
